package markdown

import (
	"fmt"
	"reflect"
	"strings"
)

// Response --> responses
type Response struct {
	Description string                    `json:"description,omitempty"`
	Headers     map[string]*SchemaOrItems `json:"headers,omitempty"`
	Schema      *SchemaOrItems            `json:"schema,omitempty"`
	Examples    interface{}               `json:"example,omitempty"`
	Content     map[string]MediaType      `json:"content,omitempty"`
	Links       map[string]Link           `json:"links,omitempty"`
}

func (response *Response) responseParam(code string, resolver *resolver) (resParamTable, resParamDesc string) {
	parser := ParamParser{
		ParamTypePosition: ResponseHeaderParam,
		resolver:          resolver,
	}
	// 响应头列表
	headerText := ""
	for name, header := range response.Headers {
		paramInfo := parser.newParam(name, header, []string{})
		headerText += strings.Join(paramInfo.TableRow, "")
	}
	// openapi3.0
	if response.Content != nil {
		response.Schema = new(SchemaOrItems)
		for mediaType, content := range response.Content {
			if "application/json" == mediaType {
				parser.MediaType = mediaType
				response.Schema = content.Schema
			}
		}
	}
	if response.Schema == nil {
		response.Schema = new(SchemaOrItems)
	}
	// 响应参数块
	response.Schema.Description += fmt.Sprintf("<br>%s", response.Description)
	parser.ParamTypePosition = CodeParam
	paramInfo := parser.newParam(code, response.Schema, []string{})
	resParamTable = strings.Join(paramInfo.TableRow, "")
	// 组装示例及参数表
	parser.ParamTypePosition = ResponseParam
	paramInfo = parser.newParam(code, response.Schema, []string{})
	mdText := strings.Join(paramInfo.TableRow[1:], "")
	// 字段说明
	if mdText != "" {
		mdText = fmt.Sprintf(templateParamDesc, mdText)
	}
	// Headers
	if headerText != "" {
		mdText += fmt.Sprintf(headerList, headerText)
	}
	// 参数示例
	if response.Examples != nil && !reflect.DeepEqual(response.Examples, reflect.Zero(reflect.TypeOf(response.Examples)).Interface()) {
		resParamDesc = fmt.Sprintf(templateExResp, code, response.Examples, mdText)
		return resParamTable, resParamDesc
	}
	exText := serialization(paramInfo.Value)
	resParamDesc = fmt.Sprintf(templateExResp, code, exText, mdText)
	return resParamTable, resParamDesc
}
